package edu.mtu.citizenscience.streamapplication.activity.main;

import edu.mtu.citizenscience.streamapplication.activity.DBHelper;
import edu.mtu.citizenscience.streamapplication.activity.HTMLView;
import edu.mtu.citizenscience.streamapplication.activity.R;
import edu.mtu.citizenscience.streamapplication.activity.R.layout;
import edu.mtu.citizenscience.streamapplication.activity.R.menu;

import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;

public class SCRoadDataActivity extends Activity {
	
	// for finding ui elements
	private EditText otherLowText;
	private Spinner drainageControl;
	private EditText repairDrainage;
	private EditText crossingWidth;
	private Spinner roadSurface;
	private RadioGroup mainRadioGroup;
	private RadioGroup lowRadioGroup;
	private EditText leftLength;
	private EditText rightLength;
	private Spinner leftSlope;
	private Spinner rightSlope;
	private Spinner leftVegetation;
	private Spinner rightVegetation;
	private EditText averageWidth;
	private TextView header;
	
	// Data base variables
	private DBHelper myDbHelper;
	private Long rowID;
	public static final String ROW_ID = "ROW_ID";
    private Cursor report;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// custom view stuff
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // %^&*
		
		setContentView(R.layout.activity_scroad_data);
		
		// custom view stuff
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title); // %^&*
		
		// DB
		myDbHelper = new DBHelper(this);
		myDbHelper.open();
		
		// custom view stuff
		header = (TextView) findViewById(R.id.header_text); // %^&*
		header.setText("Road Data"); // %^&*
		
		// find elements
		otherLowText = (EditText) findViewById(R.id.otherLowText);
		repairDrainage = (EditText) findViewById(R.id.repairDrainage);
		drainageControl = (Spinner) findViewById(R.id.drainageControl);
		crossingWidth = (EditText) findViewById(R.id.crossingWidth);
		roadSurface = (Spinner) findViewById(R.id.roadSurface);
		mainRadioGroup = (RadioGroup) findViewById(R.id.mainRadioGroup);
		lowRadioGroup = (RadioGroup) findViewById(R.id.streamRadioGroup);
		leftLength = (EditText) findViewById(R.id.leftLength);
		rightLength = (EditText) findViewById(R.id.rightLength);
		leftSlope = (Spinner) findViewById(R.id.leftSlope);
		rightSlope = (Spinner) findViewById(R.id.rightSlope);
		leftVegetation = (Spinner) findViewById(R.id.leftVegetation);
		rightVegetation = (Spinner) findViewById(R.id.rightVegetation);
		averageWidth = (EditText) findViewById(R.id.averageWidth);
		
		// spinner listener
		SpinnerOnItemSelectedListener spinnerListener = new SpinnerOnItemSelectedListener();
		spinnerListener.loadView(repairDrainage,"Need Repair");
		drainageControl.setOnItemSelectedListener(spinnerListener);
		
		repairDrainage.setEnabled(false);
		otherLowText.setEnabled(false);
		
		// radio group thing
	    lowRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() 
	    {
	        public void onCheckedChanged(RadioGroup group, int checkedId) {
	            if(checkedId == R.id.otherLow)
	            	otherLowText.setEnabled(true);            
	            else
	            	otherLowText.setEnabled(false);
	        }
	    });
	    
	    // DB
	    rowID = this.getIntent().getLongExtra(this.ROW_ID, -1);
	    populateFields();
	    
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.scroad_data, menu);
		return true;
	}
	
	// DB
    private void populateFields() {
    	report = myDbHelper.fetchReport(rowID, "Road_Data");
    	// if there is data in the report then fill it in
        if (report.getCount() == 1) {
        	// set ui elements 
        	crossingWidth.setText(Integer.toString(report.getInt(report.getColumnIndexOrThrow("width_at_crossing"))));
        	roadSurface.setSelection(getSpinnerIndex(roadSurface, report.getString(report.getColumnIndexOrThrow("road_surface"))));
        	// set radio buttons
        	if(report.getString(report.getColumnIndexOrThrow("maintenance")).equals("Seasonal")){
        		mainRadioGroup.check(R.id.seasonal);
        	}
        	else{
        		mainRadioGroup.check(R.id.yearRound);
        	}
        	if(report.getString(report.getColumnIndexOrThrow("location_low_point")).equals("At Stream")){
        		lowRadioGroup.check(R.id.atStream);
        	}
        	else{
        		otherLowText.setEnabled(true);
        		lowRadioGroup.check(R.id.otherLow);
        		otherLowText.setText(report.getString(report.getColumnIndexOrThrow("location_low_point")));
        	}
        	// set spinner
            if(getSpinnerIndex(drainageControl,report.getString(report.getColumnIndexOrThrow("existing_drainage"))) == -1){
            	drainageControl.setEnabled(true);
            	drainageControl.setSelection(getSpinnerIndex(drainageControl, "Need Repair"));
            	repairDrainage.setText(report.getString(report.getColumnIndexOrThrow("existing_drainage")));
            }
            else{
            	drainageControl.setSelection(getSpinnerIndex(drainageControl, report.getString(report.getColumnIndexOrThrow("existing_drainage"))));
            }
        	
            // set other texts
        	leftLength.setText(Integer.toString(report.getInt(report.getColumnIndexOrThrow("l_approach_length"))));
        	rightLength.setText(Integer.toString(report.getInt(report.getColumnIndexOrThrow("r_approach_length"))));
        	leftSlope.setSelection(getSpinnerIndex(leftSlope, report.getString(report.getColumnIndexOrThrow("l_approach_slope"))));
        	rightSlope.setSelection(getSpinnerIndex(rightSlope, report.getString(report.getColumnIndexOrThrow("r_approach_slope"))));
        	leftVegetation.setSelection(getSpinnerIndex(leftVegetation, report.getString(report.getColumnIndexOrThrow("l_ditch_vegetation"))));
        	rightVegetation.setSelection(getSpinnerIndex(rightVegetation, report.getString(report.getColumnIndexOrThrow("r_ditch_vegetation"))));
        	averageWidth.setText(Integer.toString(report.getInt(report.getColumnIndexOrThrow("width_of_grade"))));
        }
    }
    
    // DB
    private long saveRoad(){
    	
    	// Handle the radio button group for maintenance
    	String main;
    	if(mainRadioGroup.getCheckedRadioButtonId() == R.id.seasonal){
    		main = "Seasonal";
    	}
    	else{
    		main = "Year Round";
    	}
    	// Handle the drainage spinner
    	String drainage;
    	if(drainageControl.getSelectedItem().toString().equals("Need Repair")){
    		drainage = repairDrainage.getText().toString();
    	}
    	else{
    		drainage = drainageControl.getSelectedItem().toString();
    	}
    	// Handle Low point other
    	String lowPoint;
    	if(lowRadioGroup.getCheckedRadioButtonId() == R.id.otherLow){
    		lowPoint = otherLowText.getText().toString();
    	}
    	else{
    		lowPoint = "At Stream";
    	}
    	int cw;
    	int ll;
    	int rl;
    	int aw;
    	// set up text boxes
    	if(crossingWidth.getText().toString().length() == 0){
    		cw = 0;
    	}
    	else{
    		cw = Integer.parseInt(crossingWidth.getText().toString());
    	}
    	if(leftLength.getText().toString().length() == 0){
    		ll = 0;
    	}
    	else{
    		ll = Integer.parseInt(leftLength.getText().toString());
    	}
    	if(rightLength.getText().toString().length() == 0){
    		rl = 0;
    	}
    	else{
    		rl = Integer.parseInt(rightLength.getText().toString());
    	}
    	if(averageWidth.getText().toString().length() == 0){
    		aw = 0;
    	}
    	else{
    		aw = Integer.parseInt(averageWidth.getText().toString());
    	}
    	// if there is no report then create one
		if(report.getCount() == 0){
			myDbHelper.createRoad(rowID,
					cw,
					roadSurface.getSelectedItem().toString(),
					ll,
					rl,
					leftSlope.getSelectedItem().toString(),
					rightSlope.getSelectedItem().toString(),
					main, 
					lowPoint, 
					drainage, 
					leftVegetation.getSelectedItem().toString(), 
					rightVegetation.getSelectedItem().toString(),
					aw);
		}
		// there is a report so update it
		else{
			myDbHelper.updateRoad(rowID,
					cw,
					roadSurface.getSelectedItem().toString(),
					ll,
					rl,
					leftSlope.getSelectedItem().toString(),
					rightSlope.getSelectedItem().toString(),
					main, 
					lowPoint, 
					drainage, 
					leftVegetation.getSelectedItem().toString(), 
					rightVegetation.getSelectedItem().toString(),
					aw);
		}
		return rowID;
    } 
	
	/** Called when the user clicks the Continue button */
	public void cont(View view) {
		// DB
		rowID = saveRoad();
		myDbHelper.close();
		
		this.finish();
	}
	
	public void cancel(View view) {
		this.finish();
	}
	
	// helper for dealing with spinners gets the index of the str in the spinner
	private int getSpinnerIndex(Spinner spin, String str) 
    {
    	Adapter adapter = spin.getAdapter();
    	for(int i=0; i < adapter.getCount(); i++)
    	{
    		if(adapter.getItem(i).toString().equals(str))			
    			return i;
    	}
    	return -1;
    }
	
	@Override
    public void onBackPressed() {
        super.onBackPressed();   
        myDbHelper.close();
        this.finish();
    }
	
	// set up the custom title question mark help
	public void tutorial(View view){
		Intent intent = new Intent(this, HTMLView.class);
		intent.putExtra(HTMLView.PATH, "file:///android_asset/road.html");
		this.startActivity(intent);
	}

}
